// proxySubShopPartner.js
const app = getApp()
const util = require("../../utils/util.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopid:'',
    agent:{},
    agentShow:false,
    serive:{},
    seriveShow: false,
    saleman:{},
    salemanShow: false,

    shopWayshow:false,
    actionShow: false,
    type:'shop',
    state:"add",
    name:'',
    id: '',
    idError:'',
    telphone:'',
    commission:'',
    disabled:false,

    memberShow:false,
    member:[],
    shopcommission:'',

    staffRateDialog: false,
    staffRate: '',

    surplusRate: '',
  },
  // 表单数值改变
  onChange: function (detail, txt) {// detail 为当前输入的值
    var that = this;
    that.setData({
      [detail]: txt
    })
  },
  idChange: function (event) {
    this.onChange('id', event.detail)
  },
  nameChange: function (event) {
    this.onChange('name', event.detail)
  },
  telChange: function (event) {
    this.onChange('telphone', event.detail)
  },
  commissionChange: function (event) {
    this.onChange('commission', event.detail)
  },
  staffRateChange: function (event) {
    this.onChange('staffRate', event.detail)
  },
  clearErr: function () {
    this.setData({
      idError: ""
    })
  },
  rateLimit: function (event) {
    var that = this;
    var type = that.data.type;
    var agentRate = that.data.agentRate;
    var shopRate = that.data.agent ? that.data.agent.commission : 0;
    var engRate = that.data.serive ? that.data.serive.engCommission : 0;
    var saleRate = that.data.saleman ? that.data.saleman.salesmanCommission : 0;
    that.setData({
      surplusRate: agentRate - shopRate - engRate - saleRate
    })
    var surplus = '';
    if(type=='shop'){
      surplus = agentRate - engRate - saleRate
      if (event.detail.value > surplus) {
        that.setData({
          commission: surplus
        })
      }
      if (event.detail.value < 0) {
        this.setData({
          commission: 0
        })
      }
    } else if (type == 'engineer') {
      surplus = agentRate - shopRate - saleRate
      if (event.detail.value > surplus) {
        that.setData({
          staffRate: surplus
        })
      }
      if (event.detail.value < 0) {
        this.setData({
          staffRate: 0
        })
      }
    } else if (type == 'salesman') {
      surplus = agentRate - shopRate - engRate
      if (event.detail.value > surplus) {
        that.setData({
          staffRate: surplus
        })
      }
      if (event.detail.value < 0) {
        this.setData({
          staffRate: 0
        })
      }
    }
  },
  shopWayShow:function(e){
    var type = e.currentTarget.dataset.type;
    var state = e.currentTarget.dataset.state;
    this.setData({
      type: type,
      state: state,
      shopWayshow: true
    })
  },
  shopWayHide: function() {
    this.setData({ shopWayshow: false });
  },
  // 打开商家添加修改弹窗编辑
  manage: function (e) {
    var type = e.currentTarget.dataset.type;
    var state = e.currentTarget.dataset.state;
    if(state == 'update'){
      this.setData({
        name: this.data.agent.name || '',
        telphone: this.data.agent.telphone || '',
        commission: this.data.agent.commission || '',
      })
    }
    this.setData({
      type: type,
      state: state,
      actionShow: true,
      shopWayshow: false
    })
  },
  actionClose: function () {
    this.setData({
      actionShow: false,
      name: "",
      id: '',
      telphone: "",
      commission: '',
      idError: ''
    })
    this.list();
  },
  manageConfirm:function(){
    var that = this;
    var state = that.data.state;
    if (state == "add"){
      that.verifyID();
    } else if (state == "update"){
      that.Toadd();
    } else if (state == "delete"){
      if (that.data.id !==""){
        that.verifyID();
      }else{
        that.Todelete();
      }
    }
  },
  // 验证ID
  verifyID: function () {
    var that = this;
    var id = that.data.id;
    var state = that.data.state;
    var data = { id: id };
    if ( id !== '' ) {
      app.post('agent/verifyShopID', data).then((res) => {
        wx.hideLoading();
        if (res.code == 200) {
          if(state == 'add'){
            that.Toadd()
          }
          if(state == 'delete'){
            that.Todelete()
          }
        } else {
          that.setData({
            idError: res.message
          })
        }
      }).catch((errMsg) => {
        console.log(errMsg);
        wx.hideLoading();
        wx.showToast({
          title: "网络错误",
          icon: 'loading',
          duration: 2000
        })
      })
    } else {
      that.setData({
        idError: '请输入用户ID'
      })
    }
  },
  // 添加修改商家
  Toadd: function () {
    var that = this;
    var type = that.data.type;
    var id = '';
    var commission = '';
    if (that.data.state=="add"){
      id = that.data.id;
      commission = that.data.shopcommission
    } else if(that.data.state=='update'){
      id = that.data.agent.id;
      commission = that.data.commission
      that.setData({
        shopcommission: commission
      })
    }
    var data = {
      type: type,
      id: that.data.shopid,
      uid: id,
      name: that.data.name,
      telphone: that.data.telphone,
      commission: commission,
    };
    that.manageAPI(JSON.stringify(data))   
  },
  // 删除人员
  Todelete: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    wx.showModal({
      title: '提示',
      content: '请确认是否删除',
      success:function(res){
        if(res.confirm){
          var data = {
            type: type,
            id: that.data.shopid,
            uid: '',
            name: '',
            telphone: '',
            commission: ''
          };
          that.manageAPI(JSON.stringify(data))
        }
      }
    })
  },
  // 添加工作人员列表
  addmember: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var state = e.currentTarget.dataset.state;
    this.setData({
      type: type,
      state: state,
      memberShow: true,
      shopWayshow: false
    })
    var data = {type:type};
    wx.showLoading({
      title: '加载中...',
    })
    // 选择自己成员
    app.post('agent/getAgentEmployee', data).then((res) => {
      wx.hideLoading();
      if (res.code == 200) {
        var member = [];
        for(var i = 0; i<res.list.length;i++){
          member.push({
            name: res.list[i].name !== '' ? res.list[i].name : res.list[i].nickName,
            subname: '(' + res.list[i].id + ')',
            id: res.list[i].id,
            openid: res.list[i].openid,
            nickName: res.list[i].nickName
          })
        }
        that.setData({
          member: member
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
      wx.hideLoading();
      wx.showToast({
        title: "网络错误",
        icon: 'loading',
        duration: 2000
      })
    })
  },
  memberClose() {
    this.setData({ memberShow: false });
  },
  // 添加人员
  memberlist: function (event) {
    var that = this;
    var type = that.data.type;
    var commission = type == "shop" ? that.data.shopcommission : that.data.commission;
    var data = {
      type: type,
      id: that.data.shopid,
      uid: event.detail.id,
      name: event.detail.name,
      telphone: event.detail.telphone,
      commission: commission,
    };
    that.manageAPI(JSON.stringify(data))   
  },
  // 触发工作人员修改比例弹窗
  ToeditRate: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var value = type == "engineer" ? that.data.serive.engCommission : that.data.saleman.salesmanCommission;
    that.setData({
      type: type,
      staffRateDialog: true,
      staffRate: value
    })
  },
  // 修改备注，描述
  staffRateUpdate: function () {
    var that = this;
    var type = that.data.type;
    var id = '';
    var name = '';
    var telphone = '';
    if (that.data.type == "engineer") {
      id = that.data.serive.id;
      name = that.data.serive.name;
      telphone = that.data.serive.telphone;
    } else if (that.data.type == 'salesman') {
      id = that.data.saleman.id;
      name = that.data.saleman.name;
      telphone = that.data.saleman.telphone;
    }
    var data = {
      type: type,
      id: that.data.shopid,
      uid: id,
      name: name,
      telphone: telphone,
      commission: that.data.staffRate,
    };
    that.manageAPI(JSON.stringify(data))
  },
  // 关闭比例弹窗
  staffUpdateClose() {
    this.setData({ staffRateDialog: false });
  },
  manageAPI:function(data){
    var that = this;
    var data = JSON.parse(data);
    wx.showLoading({
      title: '加载中...',
    })
    app.post('agent/submitShopStaff', data).then((res) => {
      wx.hideLoading();
      if (res.code == 200) {
        that.actionClose();
      } else {
        wx.showToast({
          title: res.message,
          icon: 'loading',
          duration: 2000
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);
      wx.hideLoading();
      wx.showToast({
        title: "网络错误",
        icon: 'loading',
        duration: 2000
      })
    })
  },
  // 计算剩余比例
  surplus:function(){
    var that = this;
    var agentRate = that.data.agentRate;
    var shopRate = that.data.agent ? that.data.agent.commission : 0;
    var engRate = that.data.serive ? that.data.serive.engCommission : 0;
    var saleRate = that.data.saleman ? that.data.saleman.salesmanCommission : 0;
    that.setData({
      surplusRate: agentRate - shopRate - engRate - saleRate
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      shopid:options.id,
      shopcommission: options.commission,
      agentRate: app.globalData.agentRate
    })
    that.list();
  },
  // 没有数据
  nodata:function(){
    var that = this;
    if (that.data.agent !== null && JSON.stringify(that.data.agent) !== '{}') {
      that.setData({
        agentShow: true
      })
    }else{
      that.setData({
        agentShow: false
      })
    }
    if (that.data.serive !== null && JSON.stringify(that.data.serive) !== '{}') {
      that.setData({
        seriveShow: true
      })
    }else{
      that.setData({
        seriveShow: false
      })
    }
    if (that.data.saleman !== null && JSON.stringify(that.data.saleman) !== '{}') {
      that.setData({
        salemanShow: true
      })
    }else{
      that.setData({
        salemanShow: false
      })
    }
  },
  // 商家及工作人员信息
  list: function () {
    var that = this;
    var data = { id: that.data.shopid };
    app.post('agent/shopStaff', data).then((res) => {
      wx.hideLoading();
      if (res.code == 200) {
        that.setData({
          agent: res.data.shop,
          serive: res.data.engineer,
          saleman: res.data.salesman,
        })
        that.nodata();
        that.surplus();
      }
    }).catch((errMsg) => {
      console.log(errMsg);
      wx.hideLoading();
      wx.showToast({
        title: "网络错误",
        icon: 'loading',
        duration: 2000
      })
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.list();
    wx.stopPullDownRefresh()
  }
})